package com.kinggm.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/testRedisson")
public class RedissonDemoController {

    @Resource
    private RedissonClient redissonClient;

    @GetMapping("/aa")
    public String testA() {
        // 获取锁 制定锁名称 (RLock 支持重入)
        RLock lock = redissonClient.getLock("REDIS_LOCK");
        try {
            // 尝试获取锁  参数①获取锁的最大等待时间   ②锁自动释放时间  ③时间单位
            boolean b = lock.tryLock(1, 10, TimeUnit.SECONDS);
            if (b) {
                try {
                    System.out.println("获取锁成功！");
                    TimeUnit.SECONDS.sleep(5);
                    // 测试锁重入
                    bb(lock);
                    return "获取锁成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }


        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "获取锁失败";
    }

    private void bb(RLock lock) {
        try {
            boolean b = lock.tryLock(1, 10, TimeUnit.SECONDS);
            try {
                if (b) {
                    System.out.println("锁重入成功");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("锁重入失败");
        }

    }

}
